package com.warrior.service;

import com.warrior.entity.ArticleEntity;
import com.warrior.respository.IArticleRepository;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by Shawn on 2017/3/21.
 */
@Service
public class ArticleService {

    private static final Logger logger = LogManager.getLogger(ArticleService.class.getName());

    @Autowired
    private IArticleRepository articleRepository;

    /**
     * 添加一篇文章
     *
     * @param articleEntity 文章entity
     * @return ArticleEntity
     */
    public ArticleEntity saveArticle(ArticleEntity articleEntity) {
        if (logger.isDebugEnabled()) {
            logger.debug("saveArticle(ArticleEntity articleEntity={}) - start", articleEntity); //$NON-NLS-1$
        }

        ArticleEntity save = this.articleRepository.save(articleEntity);

        if (logger.isDebugEnabled()) {
            logger.debug("saveArticle(ArticleEntity) - end"); //$NON-NLS-1$
        }
        return save;
    }


    /**
     * 根据id找到一篇文章
     *
     * @param articleId 文章id
     * @return ArticleEntity
     */
    public ArticleEntity findArticleById(String articleId) {
        if (logger.isDebugEnabled()) {
            logger.debug("findArticleById(String articleId={}) - start", articleId); //$NON-NLS-1$
        }

        ArticleEntity articleEntity = this.articleRepository.findArticleById(articleId);

        if (logger.isDebugEnabled()) {
            logger.debug("findArticleById(String) - end"); //$NON-NLS-1$
        }
        return articleEntity;
    }

    @Transactional
    public Page<ArticleEntity> findAllArticle(int size,int page,String orderType){
        Sort sort = new Sort(Sort.Direction.ASC, "createdAt");
        if ("desc".equals(orderType)) {
            sort = new Sort(Sort.Direction.DESC, "createdAt");
        }
        //设置分页参数
        Pageable pageable = new PageRequest(page, (size <= 0) ? 3 : size, sort);
        Page<ArticleEntity> articleEntities = this.articleRepository.findAll(pageable);
        return articleEntities;
    }

    @Transactional
    public void deleteArticle(String id){
        this.articleRepository.delete(id);
    }

}
